package com.liveinstars.quhui.application.endpoint;

import com.liveinstars.api.dto.InitModel;
import com.liveinstars.api.facade.AppConfigApi;
import com.liveinstars.quhui.business.appconfig.service.AppConfigDomainService;
import com.onepiece.shipelves.common.enums.App;
import com.onepiece.shipelves.common.enums.SystemExceptionEnum;
import com.onepiece.shipelves.common.utils.Headers;
import com.onepiece.shipelves.common.utils.JsonUtil;
import com.onepiece.shipelves.common.utils.UserAgentUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/quhui")
public class AppConfigEndpoint implements AppConfigApi {
    @Autowired
    AppConfigDomainService appConfigDomainService;

    @Override
    public String init(@RequestBody InitModel model,
                       @RequestHeader("from") String from,
                       @RequestHeader(Headers.USER_AGENT) String ua) {
        Map<String, Object> tokenInfo = new HashMap<>(9);
        checkInitParams(model);
        String osVersionNum = ua != null ? UserAgentUtil.getOSVersionNum(ua) : "";
        if (!StringUtils.isEmpty(ua) && ua.length() > 250) {
            ua = ua.substring(0, 250);
        }

        addInitInfo(model.getVersion(), from, tokenInfo, ua);

        return JsonUtil.toJson(tokenInfo);
    }


    private void addInitInfo(String version, String from, Map<String, Object> tokenInfo, String ua) {
        Map<String, Object> versionInfo = appConfigDomainService.checkAppVersionWithAppCode(version, from, App.transToAppCode(ua));
        tokenInfo.putAll(versionInfo);
//        AppAdPopConfigInfo popAdInfo = appConfigService.findLastAppAdPopConfigInfoByAppAndVersion(from, version);
//        tokenInfo.put("flash", popAdInfo);

    }

    private void checkInitParams(InitModel model) {
        if (model.isParamsAllEmpty()) {
            throw SystemExceptionEnum.ILLEGAL_REQUEST_PARAM.ex;
        }
    }
}
